<?php
class Answer_Service_Question extends Phpfox_Service
{
    function __construct()
    {
        $this->_sTable = Phpfox::getT('brodev_answer_question');
        $this->_sTableParent = Phpfox::getT('brodev_answer_category');
        $this->_sTableUser = Phpfox::getT('user');
    }

    /**
     * get question from database
     * @param string $sFields
     * @param array $aCondition
     * @param int $iPage
     * @param int $iLimit
     * @return array
     */
    public function getList($sFields = '*', $aCondition = array(), $iPage = 1, $iLimit = 20)
    {
        if (empty($iPage)) {
            $iPage = 1;
        }
        $iCount = $this->database()
            ->select('COUNT(*)')
            ->from($this->_sTable, 'c')
            ->where($this->getCondition($aCondition))
            ->execute('getField');
        $aRecords = $this->database()
            ->select($sFields . ', c.name as category_name, u.user_image as image, u.full_name as full_name')
            ->from($this->_sTable, 'q')
            ->where($this->getCondition($aCondition))
            ->leftJoin($this->_sTableParent, 'c', 'q.category_id = c.id')
            ->leftJoin($this->_sTableUser, 'u', 'q.user_id = u.user_id')
            ->limit($iPage, $iLimit, $iCount)
            ->order('created')
            ->execute('getRows');
        $aRecords = $this->processRows($aRecords);
        return array(
            'data' => $aRecords,
            'count' => $iCount
        );
    }

    /**
     * get categories from database without page
     * @param string $sFields
     * @param array $aConditions
     * @param string $sOrder
     * @param int $iLimit
     * @return array
     */
    public function getListNoPage($sFields = 'q.*', $aConditions = array(), $sOrder = 'time_stamp', $iLimit = 100000)
    {
        $aRecords = $this->database()
            ->select($sFields . ', c.name as category_name, u.user_image as image, u.user_name as user_name, u.full_name as full_name, u.user_id')
            ->from($this->_sTable, 'q')
            ->where($this->getCondition($aConditions))
            ->leftJoin($this->_sTableParent, 'c', 'q.category_id = c.id')
            ->leftJoin($this->_sTableUser, 'u', 'q.user_id = u.user_id')
            ->order($sOrder)
            ->limit($iLimit)
            ->execute('getRows');

        $aRecords = $this->processRows($aRecords);

        return array(
            'data' => $aRecords
        );
    }

    /**
     * add fields to result
     * @param array $aRows
     * return array
     */
    private function processRows($aRows)
    {
        foreach ($aRows as $iKey => $aRow) {
            $aRows[$iKey]['link'] = Phpfox::getLib('url')->makeUrl('answer.question.view', array('id' => $aRow['id']));
            $aRows[$iKey]['answer'] = Phpfox::getService('answer.answer')->getTotal($aRow['id']);
            $aLike = Phpfox::getService('like')->getLikes('answer', $aRow['id']);
            if (count($aLike) > 0) {
                $aRows[$iKey]['isLiked'] = true;
            } else {
                $aRows[$iKey]['isLiked'] = false;
            }
            $aRows[$iKey]['point'] = Phpfox::getService('answer.point')->getPoint($aRow['user_id']);
            $aRows[$iKey]['label'] = Phpfox::getService('answer.level')->getLabel($aRow['user_id']);
            $aRows[$iKey]['aFeed'] = array(
                'feed_display' => 'mini',
                //'comment_type_id' => 'answer',
                'privacy' => "",
                //'comment_privacy' => "",
                'like_type_id' => 'answer',
                'feed_is_liked' => $aRows[$iKey]['isLiked'],
                'feed_is_friend' => false,
                'item_id' => $aRow['id'],
                'user_id' => $aRow['user_id'],
                //'total_comment' => 0,
                'feed_total_like' => count($aLike),
                'total_like' => count($aLike),
                'feed_link' => "#",
                'feed_title' => $aRow['title']
            );
        }
        return $aRows;
    }

    /**
     * convert array to condition string
     * @param array $aCondition
     * @return string
     *
     */
    private function getCondition($aCondition)
    {
        $sCondition = "1=1";
        foreach ($aCondition AS $Array) {
            $sCondition .= " AND " . $Array;
        }
        return $sCondition;
    }

    /**
     * insert or update category to database
     * @param $aVals
     * @param $iId
     * @return bool
     */
    public function saveDatabase($aVals)
    {
		$iId = $aVals['id'];		
        $aCondition = array('id = ' . (int)$iId);
        $oParseInput = Phpfox::getLib('parse.input');
        if ((isset($aVals['category_id'])) && ($aVals['category_id'] == 0)) {
            return Phpfox_Error::set(Phpfox::getPhrase('answer.you_must_choose_category'));
        }
        if (!$this->isExist($aCondition)) {
            $aVals['time_stamp'] = PHPFOX_TIME;
            $aVals['view'] = 0;
            $aVals['detail'] = (empty($aVals['detail']) ? null : $oParseInput->prepare($aVals['detail']));		
			$allowedExts = array("gif", "jpeg", "jpg", "png");
			$temp = explode(".", $_FILES["image"]["name"]);
			$extension = end($temp);
			
			if ((($_FILES["image"]["type"] == "image/gif")
			|| ($_FILES["image"]["type"] == "image/jpeg")
			|| ($_FILES["image"]["type"] == "image/jpg")
			|| ($_FILES["image"]["type"] == "image/pjpeg")
			|| ($_FILES["image"]["type"] == "image/x-png")
			|| ($_FILES["image"]["type"] == "image/png"))
			&& ($_FILES["image"]["size"] < 2000000)
			&& in_array($extension, $allowedExts)) {
			  if ($_FILES["image"]["error"] > 0) {
				echo "Return Code: " . $_FILES["image"]["error"] . "<br>";
			  } else {
				/*echo "Upload: " . $_FILES["image"]["name"] . "<br>";
				echo "Type: " . $_FILES["image"]["type"] . "<br>";
				echo "Size: " . ($_FILES["image"]["size"] / 1024) . " kB<br>";
				echo "Temp file: " . $_FILES["image"]["tmp_name"] . "<br>";
				*/
				$name_image = '';
				if (file_exists("file/pic/answer/" . $_FILES["image"]["name"])) {
					$name_image = time()."-".$_FILES["image"]["name"];
					move_uploaded_file($_FILES["image"]["tmp_name"],
				  "file/pic/answer/" .$name_image );
				} else {
					$name_image = $_FILES["image"]["name"];
				    move_uploaded_file($_FILES["image"]["tmp_name"],				  
				  "file/pic/answer/" . $_FILES["image"]["name"]);
				}
			  }
			} else {
			   echo "Invalid file";
			}
			$aVals['image'] = $name_image;
			
            $iId = $this->database()
                ->insert($this->_sTable, $aVals);
            if (!$iId) {
                return false;
            } else {
                $aPoint = array(
                    'action' => 1,
                    'question_id' => $iId,
                    'user_id' => $aVals['user_id'],
                    'answer_id' => 0,
                    'created' => date("Y-m-d H:i:s", time())

                );
                Phpfox::getService('answer.point')->saveDatabase($aPoint);
                Phpfox::getService('feed.process')->add('answer_question', $iId);
                $sCacheId = Phpfox::getLib('cache')->set('answer_tag');
                Phpfox::getLib('cache')->remove($sCacheId);
                Phpfox::getLib('cache')->remove('answer_category_', 'substr');
                return $iId;
            }
        } else {
		$deleteimage = $this->request()->get('deleteimage');
		if($deleteimage=="1"){	
			$allowedExts = array("gif", "jpeg", "jpg", "png");
			$temp = explode(".", $_FILES["image"]["name"]);
			$extension = end($temp);
			
			if ((($_FILES["image"]["type"] == "image/gif")
			|| ($_FILES["image"]["type"] == "image/jpeg")
			|| ($_FILES["image"]["type"] == "image/jpg")
			|| ($_FILES["image"]["type"] == "image/pjpeg")
			|| ($_FILES["image"]["type"] == "image/x-png")
			|| ($_FILES["image"]["type"] == "image/png"))
			&& ($_FILES["image"]["size"] < 2000000)
			&& in_array($extension, $allowedExts)) {
			  if ($_FILES["image"]["error"] > 0) {
				echo "Return Code: " . $_FILES["image"]["error"] . "<br>";
			  } else {
				$name_image = '';
				if (file_exists("file/pic/answer/" . $_FILES["image"]["name"])) {
					$name_image = time()."-".$_FILES["image"]["name"];
					move_uploaded_file($_FILES["image"]["tmp_name"],
				  "file/pic/answer/" .$name_image );
				} else {
					$name_image = $_FILES["image"]["name"];
				    move_uploaded_file($_FILES["image"]["tmp_name"],				  
				  "file/pic/answer/" . $_FILES["image"]["name"]);
				}
			  }
			} else {
			   echo "Invalid file";
			}
			$aVals['image'] = $name_image;
		}
            $this->database()->update($this->_sTable, $aVals, "id = " . $iId);
            return $iId;
        }
    }

    /**
     * get 1 question from database with condition
     * @param array $aCondition
     * @return array
     */
    public function getForEdit($aCondition)
    {
        $aQuestion = $this->database()
            ->select('q.*, q.image as question_image, c.name as category_name, u.user_image as image, u.user_name as user_name, u.full_name as full_name')
            ->from($this->_sTable, 'q')
            ->where($this->getCondition($aCondition))
            ->leftJoin($this->_sTableParent, 'c', 'q.category_id = c.id')
            ->leftJoin($this->_sTableUser, 'u', 'q.user_id = u.user_id')
            ->execute('getRow');
        $aCondition = array(
            'id = ' . (int)Phpfox::getService('answer.category')->getParentId($aQuestion['category_id'])
        );
        if (Phpfox::getService('answer.category')->getParentId($aQuestion['category_id']) != 0) {
            $aCategory = Phpfox::getService('answer.category')->getForEdit($aCondition);
            $aCategory = $aCategory['data'];
            $aQuestion['main_category'] = array(
                'id' => $aCategory['id'],
                'name' => $aCategory['name']
            );
        } else {
            $aQuestion['main_category'] = array(
                'id' => 0
            );
        }

        $aLike = Phpfox::getService('like')->getLikes('answer', $aQuestion['id']);

        if (count($aLike) > 0) {
            $aQuestion['isLiked'] = true;
        } else {
            $aQuestion['isLiked'] = false;
        }
        $aQuestion['aFeed'] = array(
            'feed_display' => 'mini',
            //'comment_type_id' => 'answer',
            'privacy' => "",
            //'comment_privacy' => "",
            'like_type_id' => 'answer',
            'feed_is_liked' => $aQuestion['isLiked'],
            'feed_is_friend' => false,
            'item_id' => $aQuestion['id'],
            'user_id' => $aQuestion['user_id'],
            //'total_comment' => 0,
            'feed_total_like' => count($aLike),
            'total_like' => count($aLike),
            'feed_link' => "#",
            'feed_title' => $aQuestion['title']
        );
        $aQuestion['answer'] = Phpfox::getService('answer.answer')->getTotal($aQuestion['id']);
        $aQuestion['link'] = Phpfox::getLib('url')->makeUrl('answer.question', array('id' => $aQuestion['id']));

        $aQuestion['point'] = Phpfox::getService('answer.point')->getPoint($aQuestion['user_id']);
        $aQuestion['label'] = Phpfox::getService('answer.level')->getLabel($aQuestion['user_id']);
        return array(
            'data' => $aQuestion
        );
    }

    /**
     * Check Exist
     * @param array $aCondition
     * @return bool
     */
    public function isExist($aCondition)
    {
        $iCount = $this->database()
            ->select('count(*) ')
            ->from($this->_sTable)
            ->where($this->getCondition($aCondition))
            ->execute('getField');
        if ($iCount > 0) {
            return true;
        } else {
            return false;
        }
    }
	
	public function getRandomQuestion($ignoreId){
		$question = $this->database()->select('*')
		->from(Phpfox::getT('brodev_answer_question'), 'q')				
		->where('q.id <> '.$ignoreId)
		->order('RAND()')
		->limit(2)
		->execute('getRows');
		return $question;		
	}
	public function countQ(){
		$question = $this->database()->select('COUNT(*) as number')
		->from(Phpfox::getT('brodev_answer_question'), 'q')				
		->execute('getRows');
		return $question;		
	}
	public function getAnswer($iId){
		$result = $this->database()->select('m.*')
				->from(Phpfox::getT('brodev_answer_question'), 'm')
				->where('m.id = '.$iId)
				->execute('getRow');
		return $result;
	}
	public function updatePoint($userid,$point){
		$aSql = array(
			'point' => $point,
		);
		$result = $this->database()->select('m.*')
				->from(Phpfox::getT('brodev_answer_userpoint'), 'm')
				->where('m.userid = '.$userid)
				->execute('getRow');
		if($result['id']>0){
			if($result['point'] < $point){
				$this->database()->update(Phpfox::getT('brodev_answer_userpoint'), $aSql, 'userid = ' . $userid);
			}
		}else{
			$this->database()->insert(Phpfox::getT('brodev_answer_userpoint'), array(
					'userid' => Phpfox::getUserId(),
					'point' => $point
				)
			);
		}
		
	}
    /**
     * delete category from database      *
     * @param $iId
     * @return bool
     */
    public function delete($iId)
    {
        $aCondition = 'a.question_id = ' . $iId;
        $aRecords = Phpfox::getService('answer.answer')->get('a.*', $aCondition);
        $aCondition = array('a.question_id = ' . $iId);
        $aRecords = $aRecords['data'];
        $this->database()
            ->delete(Phpfox::getT('notification'), 'type_id like \'%answer%\' and item_id = '. $iId);
        Phpfox::getService('notification.process')->deleteByOwner('answer_question_answer', $iId, $aRecords[0]['user_id']);
        foreach ($aRecords as $aItem) {
            Phpfox::getService('answer.answer')->delete($aItem['id']);
            $this->database()
                ->delete(Phpfox::getT('notification'), 'type_id like \'%answer%\' and item_id = '. $aItem['id']);
        }
        $aCondition = array('p.question_id = ' . $iId);
        $aRecords = Phpfox::getService('answer.point')->getListNoPage('*', $aCondition);
        $aRecords = $aRecords['data'];
        foreach ($aRecords as $aItem) {
            Phpfox::getService('answer.point')->delete($aItem['id']);
        }
        Phpfox::getService('feed.process')->delete('answer_question', $iId);
        $sCacheId = Phpfox::getLib('cache')->set('answer_tag');
        Phpfox::getLib('cache')->remove($sCacheId);
        return $this->database()->delete($this->_sTable, 'id = ' . $iId);
    }


    /**
     * Increase view when visit a question
     * @param $iId
     * @return bool
     */
    public function incView($iId)
    {
        $iView = $this->database()
            ->select('view')
            ->from($this->_sTable)
            ->where('id = ' . $iId)
            ->execute('getField');
        $aVal = array(
            'id' => $iId,
            'view' => $iView + 1
        );
        $this->saveDatabase($aVal);
        return true;
    }

    /**
     * build filer menu
     */
    public function getSectionMenu()
    {
        $aFilterMenu = array();
        $aFilterMenu = array(
            Phpfox::getPhrase('answer.home') => '',
            Phpfox::getPhrase('answer.featured_questions') => 'featured',
            Phpfox::getPhrase('answer.all_questions') => 'all',
            Phpfox::getPhrase('answer.my_questions') => 'my',
            Phpfox::getPhrase('answer.your_friend_s_questions') => 'friend'
        );
        Phpfox::getLib('template')->buildSectionMenu('answer.question', $aFilterMenu);
    }

    /**
     * count question from category
     * @param int  $iCategoryId
     * @return  int
     */
    public function countQuestion($iCategoryId)
    {
        $sId = Phpfox::getService('answer.category')->getAllId($iCategoryId);
        $iCount = $this->database()
            ->select('count(*)')
            ->from($this->_sTable)
            ->where('category_id in (' . $sId . ')')
            ->execute('getField');
        return $iCount;
    }


    public function orderTag()
    {
        $sCacheId = Phpfox::getLib('cache')->set('answer_tag');

        if (!Phpfox::getLib('cache')->get($sCacheId)) {
            $aTags = array();
            $aQuestions = $this->database()
                ->select('tag')
                ->from($this->_sTable)
                ->execute('getRows');
            foreach ($aQuestions as $aVal) {
                $aTag = explode(',', $aVal['tag']);
                foreach ($aTag as $Tag) {
                    if (!isset($aTags[trim($Tag)])) {
                        $aTags[trim($Tag)] = 1;
                    } else {
                        $aTags[trim($Tag)]++;
                    }
                }
            }

            arsort($aTags);
            $iCount = 1;
            foreach ($aTags as $sKey => $aVal) {
                if ($iCount < 5 ) {
                    $aTags[$sKey] = 'level3';
                }
                else if ($iCount < 15) {
                    $aTags[$sKey] = 'level2';
                }
                else {
                    $aTags[$sKey] = 'level1';
                }
                $iCount += 1;
            }

            $aResult = array();
            foreach ($aTags as $sKey => $Val) {
                $aResult[] = array(
                    'key' => $sKey,
                    'level' => $aTags[$sKey]
                );
            }
            shuffle($aResult);

            Phpfox::getLib('cache')->save($sCacheId,$aResult);
        }
        $sCacheId = Phpfox::getLib('cache')->set('answer_tag');
        $aResult = Phpfox::getLib('cache')->get($sCacheId);
        return $aResult;
    }

}